import "./styles.css";
import * as React from "react";
import { basename } from "./utils";
import vtkActor from "@kitware/vtk.js/Rendering/Core/Actor";
import vtkMapper from "@kitware/vtk.js/Rendering/Core/Mapper";
import vtkConeSource from "@kitware/vtk.js/Filters/Sources/ConeSource";
import vtkXMLPolyDataReader from "@kitware/vtk.js/IO/XML/XMLPolyDataReader";
import "@kitware/vtk.js/Rendering/Profiles/Geometry";
import vtkFullScreenRenderWindow from "@kitware/vtk.js/Rendering/Misc/FullScreenRenderWindow";
import vtkRenderer from "@kitware/vtk.js/Rendering/Core/Renderer";
import vtkImageData from "@kitware/vtk.js/Common/DataModel/ImageData";
import vtkPolyData from "@kitware/vtk.js/Common/DataModel/PolyData";
// import axios from 'axios';
import vtkRenderWindow from "@kitware/vtk.js/Rendering/Core/RenderWindow";
// @ts-ignore
import HttpDataAccessHelper from "@kitware/vtk.js/IO/Core/DataAccessHelper/HttpDataAccessHelper";
export async function downloadSingleData(url: string) {
  return new Promise<vtkImageData | vtkPolyData>((resolve) => {
    // @ts-ignore
    HttpDataAccessHelper.fetchBinary(url).then((binary) => {
      // const  reader= getOutReader(url)   ;
      // debugger
      // const vtpReader = reader.vtkReader.newInstance();

      const vtpReader = vtkXMLPolyDataReader.newInstance();
      // const vtpReader = vtkITKPolyDataReader.newInstance();
      vtpReader.parseAsArrayBuffer(binary);

      const polydata = vtpReader.getOutputData()  ;
      //vtpReader

      polydata.set({ name: basename(url) });
      console.log("downloadSingleData polydata::" + polydata);
      return resolve(polydata);
    });
  });
}
export default function App() {
  interface IVTKContext {
    fullScreenRenderer?: vtkFullScreenRenderWindow;
    renderWindow?: vtkRenderWindow;
    renderer?: vtkRenderer;
    coneSource?: vtkConeSource;
    vtpsource?: any,
    actor?: vtkActor;
    mapper?: vtkMapper;
  }

  const vtkContainerRef = React.useRef<HTMLDivElement | null>(null);
  const context = React.useRef<IVTKContext | null>(null);
  const [coneResolution, setConeResolution] = React.useState(6);
  const [representation, setRepresentation] = React.useState(2);
  const [myPolydata, setMypolydata] = React.useState(Object);

  // const [data, setData] =  React.useState({ hits: [] });
  // React.useEffect(() => {
  //   const fetchData = async () => {
  //     const result = await axios(
  //       'https://hn.algolia.com/api/v1/search?query=redux',
  //     );

  //     setData(result.data);
  //   };

  //   fetchData();
  // }, []);
  let url = "/vtk/res_0.vtp";
  React.useEffect(() => {
    //  let  polydata =   downloadSingleData(url);
    //  setMypolydata(polydata)
  }, []);
  React.useEffect(() => {
    if (!context.current) {
      const fullScreenRenderer = vtkFullScreenRenderWindow.newInstance({});
      const renderer = fullScreenRenderer.getRenderer();
      const renderWindow = fullScreenRenderer.getRenderWindow();
      const coneSource = vtkConeSource.newInstance({ height: 1.0 });
      let actor;
      let mapper;
      let vtpsource;
      const fetchData = async () => {
        vtpsource = await downloadSingleData(url);
        debugger;
        setMypolydata(vtpsource);
        console.log(myPolydata)
        mapper = vtkMapper.newInstance();
        // await mapper.setInputData(myPolydata);
        //@ts-ignore
        await mapper.setInputData(vtpsource  );
          actor = vtkActor.newInstance();
        await actor.setMapper(mapper);
        await renderer.addActor(actor);
      };

      fetchData();
      renderer.resetCamera();
      renderWindow.render();
      // const mapper = vtkMapper.newInstance();
      // mapper.setInputConnection(coneSource.getOutputPort());

      // const actor = vtkActor.newInstance();
      // actor.setMapper(mapper);

      // renderer.addActor(actor);
      // renderer.resetCamera();
      // renderWindow.render();

      context.current = {
        fullScreenRenderer,
        renderWindow,
        renderer,
        coneSource,
        vtpsource,
        actor,
        mapper,
      };
    }
    //useEffect()允许返回一个函数，在组件卸载时，执行该函数，清理副效应。如果不需要清理副效应，useEffect()就不用返回任何值。
    return () => {
      if (context.current) {
        const { fullScreenRenderer, coneSource, actor, mapper } =
          context.current;
        actor?.delete();
        mapper?.delete();
        coneSource?.delete();
        // vtpsource?.delete();
        fullScreenRenderer?.delete();
        context.current = null;
      }
    };
  }, [vtkContainerRef]);

  React.useEffect(() => {
    if (context.current) {
      const { vtpsource, renderWindow } = context.current;
      vtpsource?.setResolution(coneResolution);
      renderWindow?.render();
    }
  }, [coneResolution]);

 // React.useEffect(() => {
  //   if (context.current) {
  //     const { coneSource, renderWindow } = context.current;
  //     coneSource?.setResolution(coneResolution);
  //     renderWindow?.render();
  //   }
  // }, [coneResolution]);

   React.useEffect(() => {
    if (context.current) {
      const { actor, renderWindow } = context.current;
      actor?.getProperty().setRepresentation(representation);
      renderWindow?.render();
    }
  }, [representation]);
  // React.useEffect(() => {
  //   if (context.current) {
  //     const { actor, renderWindow } = context.current;
  //     actor?.getProperty().setRepresentation(representation);
  //     renderWindow?.render();
  //   }
  // }, [representation]);

  return (
    <div>
      <div ref={vtkContainerRef}>
        <table
          style={{
            position: "absolute",
            zIndex: 20,
            top: "25px",
            left: "25px",
            background: "white",
            padding: "12px",
          }}
        >
          <tbody>
            <tr>
              <td>
                <select
                  value={representation}
                  style={{ width: "80%" }}
                  onInput={(ev) =>
                    setRepresentation(Number(ev.currentTarget.value))
                  }
                >
                  <option value="0">Points</option>
                  <option value="1">Wireframe</option>
                  <option value="2">Surface</option>
                </select>
              </td>
            </tr>
            <tr>
              <td>
                <input
                  type="range"
                  min="4"
                  max="80"
                  value={coneResolution}
                  onChange={(ev) => setConeResolution(Number(ev.target.value))}
                />
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  );
}
